package leetcode.array;

import java.util.HashMap;

/**
 * @author Cheng Jun
 * Description: 给定一个整数数组和一个整数 k，判断数组中是否存在两个不同的索引 i 和 j，使得 nums [i] = nums [j]，
 * 并且 i 和 j 的差的 绝对值 至多为 k
 * <p>
 * 链接：https://leetcode-cn.com/problems/contains-duplicate-ii
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @version 1.0
 * @date 2021/12/7 15:30
 */
public class containsNearbyDuplicate {
    public static void main(String[] args) {
        System.out.println(containsNearbyDuplicate(new int[]{99, 99}, 2));
        System.out.println(containsNearbyDuplicate1(new int[]{99, 99}, 2));
    }

    static boolean containsNearbyDuplicate(int[] nums, int k) {
        boolean flag = false;
        out:
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length && j - i <= k; j++) {
                if (nums[i] == nums[j]) {
                    flag = true;
                    break out;
                }
            }
        }
        return flag;
    }

    static boolean containsNearbyDuplicate1(int[] nums, int k) {
        boolean flag = false;
        HashMap<Integer, Integer> numIndexMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (numIndexMap.containsKey(nums[i])) {
                int preIndex = numIndexMap.get(nums[i]);
                if (i - preIndex <= k) {
                    flag = true;
                    break;
                }
            }
            numIndexMap.put(nums[i], i);
        }
        return flag;
    }
}
